package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.RSAUtil;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.MobileMessageUtil;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ISysUserService userService;

    /**
     * 获取手机验证码
     * @param
     * @return
     */
    @PostMapping("/getphonecode")
    public AjaxResult getphonecode(@RequestBody LoginBody loginBody)
    {
        String randomNumbers = RandomUtil.randomNumbers(4);
        Boolean aBoolean = MobileMessageUtil.sendMobileMessage(loginBody.getPhoneNumber(), randomNumbers);
        if(aBoolean)
        {
            redisTemplate.opsForValue().set(CacheConstants.PHONE_CODE_KEY+ loginBody.getPhoneNumber(),randomNumbers,5, TimeUnit.MINUTES);
            System.out.println("发送验证码为："+randomNumbers);
            return AjaxResult.success("发送成功");
        }
        return AjaxResult.error("发送失败");
    }

    /**
     * 短信验证码登录接口
     * @param loginBody
     * @return AjaxResult
     */
    @PostMapping("/loginWithSms")
    public AjaxResult loginWithSms(@RequestBody LoginBody loginBody) {
        // 从 Redis 中获取验证码
        String cachedCode = redisTemplate.opsForValue().get(CacheConstants.PHONE_CODE_KEY+ loginBody.getPhoneNumber());

        if (cachedCode != null && cachedCode.equals(loginBody.getPhoneCode())) {
            // 验证成功，返回登录凭证（例如Token）
            String token = generateToken(loginBody.getPhoneNumber());  // 使用若依自带的Token生成逻辑
            return AjaxResult.success("登录成功", token);

        } else {
            return AjaxResult.error("验证码错误或已过期");
        }
    }
    /**
     * 根据手机号生成 JWT Token
     * @param phoneNumber 用户手机号
     * @return JWT Token
     */
    private String generateToken(String phoneNumber) {
        // 通过手机号获取用户信息
        SysUser sysUser = userService.selectUserByPhoneNumber(phoneNumber);
        if (sysUser == null) {
            throw new RuntimeException("用户不存在");
        }

        // 封装用户信息到 LoginUser 对象
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(sysUser);  // 设置用户信息
        // 生成 Token
        return tokenService.createToken(loginUser);
    }


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {

        AjaxResult ajax = AjaxResult.success();

        // 生成令牌
        String token = loginService.login(loginBody.getPhoneNumber(),loginBody.getPhoneCode());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
    /**
     * 获取公钥：前端用来密码加密
     * @return
     */
    @GetMapping("/getPublicKey")
    public RSAUtil.RSAKeyPair getPublicKey() {
        return RSAUtil.rsaKeyPair();
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions))
        {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
